package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"os"
	"yunpan/cache/log"
	"yunpan/config"
	"yunpan/mq"
	alioss "github.com/aliyun/aliyun-oss-go-sdk/oss"
	dbcli "yunpan/db"
	"yunpan/store/oss"
)

func ProcessTransfer(msg []byte) bool {
	fmt.Println("process: msg:"+string(msg))
	pubData := mq.TransferData{}
	err := json.Unmarshal(msg, &pubData)
	fmt.Println(pubData)
	if err != nil {
		log.Ob().Warn("json unmarsha1 err:"+err.Error())
		return false
	}

	fd, err := os.Open(pubData.CurLocation)
	if err != nil {
		log.Ob().Warn(err.Error())
		return false
	}

	fmt.Println("filename:"+pubData.FileName)
	option := []alioss.Option{
			alioss.ContentDisposition("attachment;filename=\""+pubData.FileName+"")}
	err = oss.Bucket().PutObject(pubData.DestLocation, bufio.NewReader(fd), option...)
	if err != nil {
		log.Ob().Warn("upload failed"+err.Error())
		return false
	}
	resp := dbcli.UpdateFileLocation(pubData.FileHash, pubData.DestLocation)

	if !resp.Suc {
		log.Ob().Warn("更新数据库异常，请检查:" + pubData.FileHash)
		return false
	}
	return true
}

func main() {
	fmt.Println("开始监听队列")
	mq.StartConsume(config.TransOSSQueueName,"transfer_oss", ProcessTransfer)
}
